package com.garlic.face.jlf.ui;

import android.Manifest;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.Tools;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;

/**
 * @author wenhui02.liu
 * @data 2018/8/8.
 */

public class SplashActivity extends BaseActivity {
    private String TAG = this.getClass().getSimpleName();

    private String[] permissions = new String[]{
            Manifest.permission.READ_PHONE_STATE,Manifest
            .permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION};
    private List<String> mPermissionList = new ArrayList<>();

    private Handler mHandler = new AuthHandler(this);

    public static final int MSG_CHECK_ATHOU = 10000;
    public static final int MSG_CHECK_PREMESSION = 40000;
    private int retry_count = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            setImmersive(true);
        } else {
            setImmersive(false);
        }
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        setContentView(R.layout.loading_activity);
        doPermissionCheck();

    }


    private void doPermissionCheck() {
        /*
         * 判断哪些权限未授予
         */
        mPermissionList.clear();
        for (String p : permissions) {
            if (ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(p);
            }
        }
        LogUtils.d("xxxxxx mPermissionList.size:"+mPermissionList.size(), true);
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    retry();
                    postToMainMsg();
                }
            }).start();

        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);
            //将List转为数组
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LogUtils.d("xxxxxx onRequestPermissionsResult "+requestCode, true);
        switch (requestCode) {
            case 1: {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //判断是否勾选禁止后不再询问
                        boolean showRequestPermission = ActivityCompat
                                .shouldShowRequestPermissionRationale(this, permissions[i]);
                        LogUtils.d("xxxxx showRequestPermission:"+showRequestPermission, true);
                        if (showRequestPermission) {//
                            //ToastUtils.toastShow("权限禁用,请打开权限", ToastUtils.ERROR);
                            //mHandler.obtainMessage(MSG_CHECK_PREMESSION).sendToTarget();
                        } else {

                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            builder.setMessage("权限禁用,请打开权限")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener(){


                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent();
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package",SplashActivity.this.getPackageName(), null);
                                    intent.setData(uri);
                                    startActivity(intent);
                                    finish();
                                }
                            });
                            builder.show();
                            //ToastUtils.toastShow("权限禁用,请打开权限", ToastUtils.ERROR);
                            //mHandler.obtainMessage(MSG_CHECK_PREMESSION).sendToTarget();
                            return;
                        }
                    }
                }

                mHandler.obtainMessage(MSG_CHECK_PREMESSION).sendToTarget();
            }
        }



    }

    public void retry() {
        Log.e(TAG, "重试次数:[" + retry_count + "]");
        retry_count++;
        if(retry_count > 3){
            postToMainMsg();
        }else {
            checkUpdate();
        }
    }

    private void checkUpdate() {
        RequestParams params = new RequestParams("http://www.miaofutech" +
                ".com:18081/api/update/check");
        params.addParameter("ChnId", Tools.getChannelFromMeta(this) + "");
        params.addParameter("PackageName", getPackageName());
        params.addParameter("VersionCode", Tools.getVersionCode() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, result);
                try {
                    JSONObject root = JSON.parseObject(result);
                    int Status = root.getIntValue("Status");
                    if (Status == 0) {
                        int new_version = root.getIntValue("VersionCode");
                        if (new_version > Tools.getVersionCode()) {
                            View rootView = View.inflate(SplashActivity.this, R.layout
                                    .download_confirm_dialog, null);
                            TextView tvMsg = (TextView) rootView.findViewById(R.id.msg);
                            tvMsg.setText(root.getString("UpdateMsg"));
                            final String downloadUrl = root.getString("Url");
                            final int versionCode = root.getIntValue("VersionCode");
                            AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity
                                    .this).setView
                                    (rootView).setCancelable(false);
                            final Dialog dialog = builder.create();
                            dialog.setCanceledOnTouchOutside(false);
                            dialog.show();
                            rootView.findViewById(R.id.done).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialog.dismiss();
                                    downloadFile(downloadUrl, versionCode);
                                }
                            });
                        } else {
                            postToMainMsg();
                        }
                    } else {
                        postToMainMsg();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    retry();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (ex!=null && !TextUtils.isEmpty(ex.getMessage())){
                    Log.e(TAG, ex.getMessage());
                    ex.printStackTrace();
                }
                //检查失败..进入校验程序
                retry();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //检查失败..进入校验程序
                postToMainMsg();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void postToMainMsg(){
        Message message = new Message();
        message.what = MSG_CHECK_ATHOU;
        mHandler.sendMessageDelayed(message, 3000);
    }

    private void downloadFile(String download_url, int versionCode) {
        String path = "/sdcard/" + getPackageName() + "/apks/";
        path += getPackageName() + "_" + versionCode + ".apk";

        View rootView = View.inflate(SplashActivity.this, R.layout
                .download_dialog, null);
        final NumberProgressBar progressBar = (NumberProgressBar) rootView.findViewById(R.id
                .number_progress_bar);
        AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity
                .this).setView
                (rootView).setCancelable(false);
        final Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        RequestParams params = new RequestParams(download_url);
        params.setAutoResume(true);//设置是否在下载是自动断点续传
        params.setAutoRename(false);//设置是否根据头信息自动命名文件
        params.setSaveFilePath(path);
        params.setExecutor(new PriorityExecutor(1, true));//自定义线程池,有效的值范围[1, 3], 设置为3时, 可能阻塞图片加载.
        params.setCancelFast(true);//是否可以被立即停止.

        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onCancelled(CancelledException arg0) {
                Toasty.error(SplashActivity.this, "下载被取消.请重新下载!").show();
                retry();
            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                Log.i("tag", "下载失败,请重试!");
                retry();
            }

            @Override
            public void onFinished() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onSuccess(File arg0) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Log.i("tag", "下载成功的时候执行" + Thread.currentThread().getName());
                try {
                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri url = FileProvider.getUriForFile(SplashActivity.this, SplashActivity.this.getApplicationContext().getPackageName() + ".fileProvider", arg0);
                    intent.setDataAndType(url, "application/vnd.android.package-archive");
                    startActivity(intent);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                if (isDownloading) {
                    progressBar.setMax((int) total);
                    progressBar.setProgress((int) current);
                    Log.i("tag", "下载中,会不断的进行回调:" + (int) (current * 100 / total));
                }
            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onWaiting() {

            }

        });
    }


    static class AuthHandler extends Handler {
        private WeakReference<SplashActivity> mActivity;

        AuthHandler(SplashActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SplashActivity activity = mActivity.get();

            switch (msg.what) {
                case MSG_CHECK_ATHOU: {
                    activity.countDownToMain();
                }
                break;
                case MSG_CHECK_PREMESSION: {
                    activity.doPermissionCheck();
                }
                break;
            }
        }
    }

    ;


    private void enterMain() {
//        ZolozUtils.getInstance(SplashActivity.this);
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }


    private void countDownToMain() {
        CountDownTimer mCountDownTimer = new CountDownTimer(1 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                enterMain();
            }
        }.start();
    }
}
